package com.bjtang.fileSync.file;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import com.bjtang.fileSync.nio.NIOClient;
import com.bjtang.fileSync.nio.SocketDto;
import com.bjtang.fileSync.util.FileConfig;
import com.bjtang.fileSync.util.FileMd5;

public class FileListener extends FileAlterationListenerAdaptor {
	private String path = FileConfig.readConfig("path").trim();
	private NIOClient nioClient = new NIOClient();

	@Override
	public void onStart(FileAlterationObserver observer) {
		super.onStart(observer);
	}

	@Override
	public void onDirectoryCreate(File directory) {
		System.out.println("新建：" + directory.getAbsolutePath());
	}

	@Override
	public void onDirectoryChange(File directory) {
		System.out.println("修改：" + directory.getAbsolutePath());
	}

	@Override
	public void onDirectoryDelete(File directory) {
		System.out.println("删除：" + directory.getAbsolutePath());
		
		
	}

	@Override
	public void onFileCreate(File file) {
		String compressedPath = file.getAbsolutePath();
		System.out.println("新建："+compressedPath);
		if (file.canRead()) {
			// 读取或重新加载文件内容
			try {
				nioClient.fileDownload(getSocketDto(file));
			} catch (IOException e) {
				System.err.println("上传至服务器失败");
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onFileChange(File file) {
		String compressedPath = file.getAbsolutePath();
		System.out.println("修改：" + compressedPath);
		if (file.canRead()) {
			// 读取或重新加载文件内容
			try {
				nioClient.fileDownload(getSocketDto(file));
			} catch (IOException e) {
				System.err.println("上传至服务器失败");
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onFileDelete(File file) {
		System.out.println("删除：" + file.getAbsolutePath());
	
			// 读取或重新加载文件内容
			try {
				String compressedPath = file.getAbsolutePath();
				SocketDto socketDto = new SocketDto();
				socketDto.setFileName(compressedPath.substring(path.length()));
				//填补32位MD5值
				socketDto.setFileMd5("00000000000000000000000000000000");
				nioClient.fileRemove(socketDto);
			} catch (IOException e) {
				System.err.println("上传至服务器失败");
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	@Override
	public void onStop(FileAlterationObserver observer) {
		super.onStop(observer);
//		System.out.println("onStop");
	}

	public SocketDto getSocketDto(File file) {
		SocketDto socketDto = new SocketDto();
		// 去掉原始前缀
		String compressedPath = file.getAbsolutePath();
		socketDto.setFileName(compressedPath.substring(path.length()));
		socketDto.setFileLastTime(file.lastModified());
		socketDto.setFileMd5(FileMd5.getMd5ByFile(file));
		socketDto.setFileSize(file.length());
		return socketDto;
	}
}
